package com.qiqidream.admin.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiqidream.admin.common.config.EncodeConfig;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * @author QiQiDream
 * @since 2020/1/6 17:40
 */
public class EncodeUtil {
    @Resource
    private static EncodeConfig encodeConfig;
    @Resource
    private static ObjectMapper objectMapper;

    private static String AlgorithmProvider = "AES/ECB/PKCS5Padding";
    private static String Algorithm = "AES";
    private static String UTF8 = "utf-8";


    private EncodeUtil() {}

    public static String encrypt(Object body) throws Exception{
        String key = encodeConfig.getKey();
        Key keySpec = new SecretKeySpec(key.getBytes(), "AES");    //两个参数，第一个为私钥字节数组， 第二个为加密方式 AES或者DES

        String iv = encodeConfig.getIv();
        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec,ivSpec);

        byte[] byteResult = cipher.doFinal(objectMapper.writeValueAsString(body).getBytes());

        StringBuilder sb = new StringBuilder();
        for (byte b : byteResult) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static String decrypt(String src) throws Exception {
        String key = encodeConfig.getKey();
        SecretKey secretKey = new SecretKeySpec(key.getBytes(UTF8), Algorithm);
        Cipher cipher = Cipher.getInstance(AlgorithmProvider);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] hexBytes = Base64Utils.decodeFromString(src);
        byte[] plainBytes = cipher.doFinal(hexBytes);
        return new String(plainBytes, UTF8);
    }
}
